﻿using System.Windows.Input;
using DDU.DataModel;
using DDU.Library;

namespace DDU.ViewModel
{
    public class ActivityAddViewModel : MainViewModel
    {
        public ActivityAddViewModel()
        {
            ActivityToAdd.ValueChanged -= ActivityToAdd_ValueChanged;
            ActivityToAdd.ValueChanged += ActivityToAdd_ValueChanged;
        }

        void ActivityToAdd_ValueChanged(object sender, PropertyArgs e)
        {
            RaisePropertyChanged(() => TimeError);
            RaisePropertyChanged(() => AddCommand);
        }

        private ActivityInfo activityToAdd = new ActivityInfo();
        public ActivityInfo ActivityToAdd
        {
            get { return activityToAdd; }
            set
            {
                activityToAdd = value;
                RaisePropertyChanged(() => ActivityToAdd);
                RaisePropertyChanged(() => TimeError);

                ActivityToAdd.ValueChanged -= ActivityToAdd_ValueChanged;
                ActivityToAdd.ValueChanged += ActivityToAdd_ValueChanged;
            }
        }

        public bool TimeError
        {
            get { return ActivityToAdd.Duration < 0; }
        }

        private void Insert(ActivityInfo entity)
        {
            Database.CollectionOfActivities.InsertOnSubmit(entity);
            Submit();
            ActivityToAdd = new ActivityInfo();
            RaisePropertyChanged(() => ActivityToAdd);
            RaisePropertyChanged(() => TimeError);
            RaisePropertyChanged(() => AddCommand);

            ActivityToAdd.ValueChanged -= ActivityToAdd_ValueChanged;
            ActivityToAdd.ValueChanged += ActivityToAdd_ValueChanged;

        }

        public ICommand AddCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return !string.IsNullOrWhiteSpace(ActivityToAdd.Title) && !TimeError; },
                    ExecuteCallback = delegate
                    {
                        Insert(ActivityToAdd);
                    }
                };
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        Navigate(BackUri);
                    }
                };
            }
        }
    }
}
